package com.codeworker.app.ui.bill;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.codeworker.app.R;
import com.codeworker.app.data.common.enums.BillTypeEnum;
import com.codeworker.app.data.common.enums.PayTypeEnum;
import com.codeworker.app.data.entity.Bill;
import com.codeworker.app.data.model.BillModel;
import com.codeworker.app.data.repository.BillRepository;
import com.codeworker.app.utils.FormatUtil;

import java.util.ArrayList;
import java.util.List;

public class BillDailySubListAdapter extends ListAdapter<Bill, BillDailySubListAdapter.BillSubViewHolder> {
    public static final String ITEM_DATA = "ITEM_DATA";

    private final BillModel billModel;

    private final BillFragment billFragment;

    private final BillDailyListAdapter.BillViewHolder billViewHolder;

    public BillDailySubListAdapter(@NonNull DiffUtil.ItemCallback<Bill> diffCallback, BillModel billModel,
                                   BillFragment billFragment, BillDailyListAdapter.BillViewHolder billViewHolder) {
        super(diffCallback);
        this.billModel = billModel;
        this.billFragment = billFragment;
        this.billViewHolder = billViewHolder;
    }

    @NonNull
    @Override
    public BillSubViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return BillSubViewHolder.create(parent);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onBindViewHolder(BillSubViewHolder holder, int position) {
        Bill current = getItem(position);
        holder.bind(current);
        billModel.setBillListLiveData(current.getDay(), current.getMonth(), current.getYear());
        billModel.getBillListLiveData().observe(billFragment.getViewLifecycleOwner(), this::submitList);
        holder.itemView.setOnClickListener(view -> {
            Intent intent = new Intent(view.getContext(), ModifyBillActivity.class);
            intent.putExtra(ITEM_DATA, current);
            view.getContext().startActivity(intent);
        });
        holder.itemView.setOnLongClickListener(view -> {
            BillRepository billRepository = new BillRepository(view.getContext());
            new AlertDialog.Builder(view.getContext())
                    .setMessage("确定删除该条账目?")
                    .setPositiveButton("确认", ((dialogInterface, data) -> {
                        billRepository.delete(current);
                        notifyItemRemoved(position);
                        notifyItemRangeRemoved(position, getItemCount() - position);
                        if (getItemCount() == 1) {
                            billViewHolder.setVisibility(View.GONE);
                        }
                    }))
                    .setNegativeButton("取消",
                            ((dialogInterface, i) ->
                                    Toast.makeText(view.getContext(), "取消", Toast.LENGTH_SHORT)
                                            .show()))
                    .show();
            return true;
        });
    }

    @Override
    public void submitList(final List<Bill> list) {
        super.submitList(list != null ? new ArrayList<>(list) : null);
    }

    static class ItemDiff extends DiffUtil.ItemCallback<Bill> {

        @Override
        public boolean areItemsTheSame(@NonNull Bill oldItem, @NonNull Bill newItem) {
            return oldItem.equals(newItem);
        }

        @Override
        public boolean areContentsTheSame(@NonNull Bill oldItem, @NonNull Bill newItem) {
            return oldItem.getId().equals(newItem.getId());
        }
    }

    static class BillSubViewHolder extends RecyclerView.ViewHolder {
        private final TextView tvPropertyName;
        private final TextView tvPropertyValue;
        private final ImageView ivPropertyIcon;

        private BillSubViewHolder(View itemView) {
            super(itemView);
            tvPropertyName = itemView.findViewById(R.id.tv_common_view_item_name);
            tvPropertyValue = itemView.findViewById(R.id.tv_common_view_item_value);
            ivPropertyIcon = itemView.findViewById(R.id.iv_common_view_item_icon);
        }

        public void bind(Bill bill) {
            String billDesc = BillTypeEnum.getBillDesc(bill.getPayType(), bill.getType());
            tvPropertyName.setText(billDesc);
            int billValue = bill.getValue();
            billValue = bill.getPayType().equals(PayTypeEnum.EXPEND.getPayTypeInDB())
                    ? -billValue : billValue;
            tvPropertyValue.setText(FormatUtil.format(billValue * 1.0 / 100));
            int resId = itemView.getContext().getResources()
                    .getIdentifier(BillTypeEnum.getBillIcon(bill.getPayType(), bill.getType()),
                            "drawable", itemView.getContext().getPackageName());
            ivPropertyIcon.setImageResource(resId);
        }

        static BillSubViewHolder create(ViewGroup parent) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.layout_common_view_item, parent, false);
            return new BillSubViewHolder(view);
        }

    }

}
